//
//  GluNetObj.m
//  CareRingApp
//
//  Created  on 2025/2/14.
//
    

#import "GluNetObj.h"
#import "ConfigModel.h"
//#import "LTPserverAPI.h"
#import "NetTools.h"

@implementation GluNetObj

-(instancetype)init
{
    if (self = [super init])
    {
        self.maxCount = 5 * 60 *100; // 100 hz, 5 minute
        self.ppgData = [NSMutableArray new];
        self.currentCount = 0;
    }
    return self;
}

/// 收集ppg数据,return yes = 收集满了
/// - Parameter newPpgs: ppg数据
-(BOOL)addPPg:(NSMutableArray<NSNumber *> *)newPPgs {
    
    if(_isEnough) {
        return _isEnough;
    }
    
    GluPPGSubObj *lastSubObj = self.ppgData.lastObject;
    if (!lastSubObj) {
        lastSubObj = [GluPPGSubObj new];
        [self.ppgData addObject:lastSubObj];
        self.start = [NSDate date];
    }
    
    for (NSNumber *ppgNum in newPPgs) {
        [lastSubObj.ppgArray addObject:ppgNum];
        self.currentCount++;
        
        if (lastSubObj.ppgArray.count >= 100) {
            // 新建
            lastSubObj.date = [NSDate date];
            
            lastSubObj = [GluPPGSubObj new];
            if (self.currentCount < self.maxCount) {
                [self.ppgData addObject:lastSubObj];
            }
        }
        
        if (self.currentCount == self.maxCount)
        {
            break;
        }
    }
    
    if (self.currentCount == self.maxCount) {
        _isEnough = YES;
        self.end = [NSDate date];
    }
    return _isEnough;
}

-(CGFloat)progressPercentValue // 百分比 0-1
{
    
//    DebugNSLog(@"进度条 %.1f, 当前 %lu, 目标 %lu", (self.currentCount * 1.0f) / (self.maxCount * 1.0f), (unsigned long)self.currentCount, (unsigned long)self.maxCount);
    
    CGFloat pross = (self.currentCount * 1.0f) / (self.maxCount * 1.0f);

    return  pross;
}


-(NSMutableDictionary *)packToReqDict
{
    NSDateFormatter *fmt1 = [NSDateFormatter new];
    fmt1.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    dict[GLU_FASTING] = @(self.fasting);
    dict[GLU_WITHIN_2_HOR] = @(self.within2HrsMeal);
    dict[GLU_STAET] = [fmt1 stringFromDate:self.start];
    dict[GLU_END] = [fmt1 stringFromDate:self.end];
    
    NSMutableArray<NSMutableDictionary *> *ppgData = [NSMutableArray new];
    dict[GLU_PPGDATA] = ppgData;
    
    for (GluPPGSubObj *ppg in self.ppgData) {
        NSMutableDictionary *ppgDict = [ppg packDict];
        if (ppgDict) {
            [ppgData addObject:ppgDict];
        }
    }

    
    return dict;
}

#pragma mark --网络请求

/// 登记设备序列号
/// - Parameters:
///   - host: 地址
///   - sn: 设备 sn
///   - age: 年龄
///   - isMale: 是否 男性
///   - weight: 体重 KG
///   - height: 身高 CM
///   - familyHistory: 是/否有糖尿病家庭病史
///   - highCholesterol: 是/否有⾼胆固醇病史
///   - ur: 1/0在sn已存如⽆该参数则默认不更新在的情况下，再次调⽤本接⼝是否更新上游数据
///   - handler: 回调
///   - servernil: 回调
+(void)gluRegPsn:(NSString *)host
              SN:(NSString *)sn
             Age:(NSUInteger)age
          Gender:(BOOL)isMale
          Weight:(NSUInteger)weight
          Height:(NSUInteger)height
   FamilyHistory:(BOOL)familyHistory
 HighCholesterol:(BOOL)highCholesterol
             Key:(NSString *)key
             MacAddr:(NSString *)mac
          Secret:(NSString *)secret
            AndComplated:(void (^)(NSHTTPURLResponse * _Nullable httpResp,  NSDictionary * _Nullable content,  NSNumber * _Nullable state , NSNumber * _Nullable lease, NSString *ltk)) handler
            AndServerNil:(void (^)(void))servernil
{

    NSString *urlSuff =  @"o2m/ppg/reg_psn";

    mac = [mac lowercaseString];
    
    NSMutableDictionary * postDict = [NSMutableDictionary new];
    postDict[@"sn"] = sn;
    postDict[@"age"] = @(age);
    postDict[@"gender"] = isMale ? @"M" : @"F" ;
    postDict[@"weight"] = @(weight);
    postDict[@"height"] = @(height);
    postDict[@"family_history"] = familyHistory ? @(1) : @(0) ;
    postDict[@"high_cholesterol"] = highCholesterol ? @(1) : @(0) ;
    
    NSString * keyEncode = [NetTools URLEncodeString:key];
    NSString * macEncode = [NetTools URLEncodeString:mac];
    postDict[@"_key"] = keyEncode;
    postDict[@"mac"] = macEncode;
    NSString *sign = [NetTools signStringWith:sn MacAddr:mac Secret:secret];
    postDict[@"_sign"] = sign;
    
    NSMutableString *arguments = [[NSMutableString alloc] init];
    NSArray<NSString *> *allKeys = postDict.allKeys;
    for (NSString * key in allKeys) {
        [arguments appendFormat:@"%@=%@", key, postDict[key]];
        if (![key isEqual:allKeys.lastObject]) {
            [arguments appendString:@"&"];
        }
    }
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/%@?%@", host, urlSuff, arguments]];
    
    
    
    DebugNSLog(@"%s url : %@", __FUNCTION__ , url);
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
    NSError *error;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];

    //第三步，连接服务器
    
//    [request setHTTPBody:jsonData];
    
    //第二步，创建请求
    WEAK_SELF
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        STRONG_SELF
        
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
        NSInteger statecode = httpResp.statusCode;
        
        NSNumber *state = nil;
        NSNumber *lease = nil; //有效的租约时间点 有效=unix时间戳, 无效=负数 需要保存
        NSString *ltk = nil;
        //            DebugNSLog(@"上传结束: %@ 结果:%ld", tableName, statecode);
        if (statecode == 301) { // app自行跳转新地址
            
            DebugNSLog(@"ecg/spe 301");
            if (data)
            {// 解析新域名
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            }
        }
        if (statecode != 200) {
            // statecode = 403 表示无账号权限,即token和上报账号不匹配
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(httpResp, nil, state,lease,ltk);
            });
            return;
        }
        
        NSDictionary* dic = nil;
//        NSArray<NSNumber *> *processedValues = nil;
        if (data)
        {
            
            dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            
            //0: 成功（重复提交也视为成功）
//            1: sn未注册
//            2: sn⽆效
            state = dic[@"state"];
            
            lease = dic[@"lease"]; //有效的租约时间点 有效=unix时间戳, 无效=负数 需要保存
           ltk = dic[@"ltk"]; // ⽤于上传测量接⼝的参数 需要保存
            
//            NSString *mid = dic[@"mid"]; //后续取结果使用

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(httpResp, dic, state,lease,ltk );
        });
    }];
    [sessionTask resume];
        
        
//    }];

}

// 发送ppg样本
-(void)gluNewSmp:(NSString *)host
       DataArray:(NSDictionary *)postDict
             Ltk:(NSString *)ltk
              SN:(NSString *)sn
             Key:(NSString *)key
             MacAddr:(NSString *)mac
          Secret:(NSString *)secret
            AndComplated:(void (^)(NSHTTPURLResponse * _Nullable httpResp,  NSDictionary * _Nullable content, NSNumber *  _Nullable state)) handler
            AndServerNil:(void (^)(void))servernil
{

    NSString *urlSuff =  @"o2m/ppg/new_smp";

    mac = [mac lowercaseString];

    // t
    NSString * ltkEncode = [NetTools URLEncodeString:ltk];
    
    NSMutableDictionary *arguDict = [NSMutableDictionary new];
    arguDict[@"ltk"] = ltkEncode;
    NSString * keyEncode = [NetTools URLEncodeString:key];
    NSString * macEncode = [NetTools URLEncodeString:mac];
    arguDict[@"_key"] = keyEncode;
    arguDict[@"mac"] = macEncode;
    arguDict[@"sn"] = sn;
    NSString *sign = [NetTools signStringWith:sn MacAddr:mac Secret:secret];
    arguDict[@"_sign"] = sign;
    
    NSMutableString *arguments = [[NSMutableString alloc] init];
    NSArray<NSString *> *allKeys = arguDict.allKeys;
    for (NSString * key in allKeys) {
        [arguments appendFormat:@"%@=%@", key, arguDict[key]];
        if (![key isEqual:allKeys.lastObject]) {
            [arguments appendString:@"&"];
        }
    }
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/%@?%@", host, urlSuff, arguments]];
 
    DebugNSLog(@"%s url : %@", __FUNCTION__ , url);
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    
   
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];

    //
    //第三步，连接服务器
    
    [request setHTTPBody:jsonData];
    
    //第二步，创建请求
    WEAK_SELF
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        STRONG_SELF
        
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
        NSInteger statecode = httpResp.statusCode;
        //            DebugNSLog(@"上传结束: %@ 结果:%ld", tableName, statecode);
        if (statecode == 301) { // app自行跳转新地址
            
            DebugNSLog(@"ecg/spe 301");
            if (data)
            {// 解析新域名
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            }
        }
        if (statecode != 200) {
            // statecode = 403 表示无账号权限,即token和上报账号不匹配
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(httpResp, nil, nil);
            });
            return;
        }
        
        NSDictionary* dic = nil;
//        NSArray<NSNumber *> *processedValues = nil;
        NSNumber *state = nil;
        if (data)
        {
            
            dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            
            state = dic[@"state"];// 0:成功 , 1:sn租约过期
            
            NSString *mid = dic[@"mid"]; //后续取结果使用
            strongSelf->_mid = mid;
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(httpResp, dic, state);
        });
    }];
    [sessionTask resume];
        
        
//    }];

}

// 获取ppg算法结果
-(void)gluAnrSmp:(NSString *)host
             Mid:(NSString *)mid
              SN:(NSString *)sn
             Key:(NSString *)key
             MacAddr:(NSString *)mac
          Secret:(NSString *)secret
            AndComplated:(void (^)(NSHTTPURLResponse * _Nullable httpResp,  NSDictionary * _Nullable content, NSNumber *  _Nullable state)) handler
            AndServerNil:(void (^)(void))servernil
{

    NSString *urlSuff =  @"o2m/ppg/anr_smp";
    mac = [mac lowercaseString];

    if (!mid) {
        handler(nil, nil, nil);
        return;
    }
    // t
//    NSString * tEncode = [[LTPserverAPI Instance_serverAPI] URLEncodeString:t];
//    NSString * tEncode = [Tools URLEncodeString:t];
//
//    NSString *arguments = [NSString stringWithFormat:@"mid=%@&t=%@", midEncode,tEncode];
//    
//    
//    
//    
//    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/%@?%@", host, urlSuff, arguments]];
    
    NSMutableDictionary *arguDict = [NSMutableDictionary new];
    
    NSString * midEncode = [NetTools URLEncodeString:mid];
    arguDict[@"mid"] = midEncode;
    NSString * keyEncode = [NetTools URLEncodeString:key];
    NSString * macEncode = [NetTools URLEncodeString:mac];
    arguDict[@"_key"] = keyEncode;
    arguDict[@"mac"] = macEncode;
    arguDict[@"sn"] = sn;
    NSString *sign = [NetTools signStringWith:sn MacAddr:mac Secret:secret];
    arguDict[@"_sign"] = sign;
    
    NSMutableString *arguments = [[NSMutableString alloc] init];
    NSArray<NSString *> *allKeys = arguDict.allKeys;
    for (NSString * key in allKeys) {
        [arguments appendFormat:@"%@=%@", key, arguDict[key]];
        if (![key isEqual:allKeys.lastObject]) {
            [arguments appendString:@"&"];
        }
    }
    
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@/%@?%@", host, urlSuff, arguments]];
    
    
    DebugNSLog(@"%s url : %@", __FUNCTION__ , url);
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"gzip" forHTTPHeaderField:@"Content-Encoding"];
    
   
//    NSError *error;
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error];

    
//    NSMutableData* bodyData = [NSMutableData data];
//    [bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
//
    //第三步，连接服务器
    
//    [request setHTTPBody:jsonData];
    
    //第二步，创建请求
    WEAK_SELF
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *sessionTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        STRONG_SELF
        
        NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
        NSInteger statecode = httpResp.statusCode;
        //            DebugNSLog(@"上传结束: %@ 结果:%ld", tableName, statecode);
        if (statecode == 301) { // app自行跳转新地址
            
            DebugNSLog(@"ecg/spe 301");
            if (data)
            {// 解析新域名
                NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            }
        }
        if (statecode != 200) {
            // statecode = 403 表示无账号权限,即token和上报账号不匹配
            dispatch_async(dispatch_get_main_queue(), ^{
                handler(httpResp, nil, nil);
            });
            return;
        }
        
        NSDictionary* dic = nil;
        NSNumber *state = nil;
//        NSArray<NSNumber *> *processedValues = nil;
        if (data)
        {
            
            dic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            
            state = dic[@"state"];// 0:成功 , 1:sn未登记
            
//            NSString *mid = dic[@"mid"]; //后续取结果使用
//            strongSelf->_mid = mid;

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            handler(httpResp, dic, state);
        });
    }];
    [sessionTask resume];
        
        
//    }];

}

@end

// 数组中的对象
@implementation GluPPGSubObj

-(instancetype)init
{
    if (self = [super init])
    {
        self.ppgArray = [NSMutableArray new];
    }
    return self;
}

-(NSMutableDictionary *)packDict {
    NSDateFormatter *fmt2 = [NSDateFormatter new];
    fmt2.dateFormat = @"HH:mm:ss";
    
    NSMutableDictionary *dict = [NSMutableDictionary new];
    dict[GLU_PPG] = self.ppgArray;
    dict[GLU_TIMESTAMP] = [fmt2 stringFromDate:self.date];
    
    return dict;
}

@end

